<template>
    <div class="container">
        <el-container>
            <el-aside class="left-menu" width="auto">
                <el-tabs tab-position="left" v-model="type">
                    <el-tab-pane 
                        v-for="(tab, index) in typeList" 
                        :key="index" 
                        :label="tab.name" 
                        :name="tab.id">
                    </el-tab-pane>
                </el-tabs>
                <el-button 
                    class="add-menu" 
                    icon="el-icon-plus" 
                    type="primary" 
                    @click="handleDialog('class', { id: 0 })">
                    <span>新增类目</span>
                </el-button>
            </el-aside>
            <el-main :class="{'no-data': getList.length <= 0}">
                <el-collapse v-model="activeClassId">
                    <el-collapse-item 
                        v-for="item of getList" 
                        :name="item.id"
                        :key="item.id" 
                        class="list-box">
                        <template slot="title">
                            <h3>{{ item.name }}</h3>
                            <span class="tpl-total">
                                ({{ item.template_list && item.template_list.length || 0 }})
                            </span>
                            <span class="control-btn">
                                <el-button 
                                    type="text" 
                                    icon="el-icon-edit"  
                                    @click.stop="handleDialog('class', item)">
                                    编辑
                                </el-button>
                                <el-button 
                                    type="text" 
                                    icon="el-icon-remove-outline" 
                                    @click.stop="handleDel('class', item.id)">
                                    删除
                                </el-button>
                                <el-button 
                                    type="text" icon="el-icon-plus"  
                                    @click.stop="handleDialog('tpl', { id: 0, group_id: item.id })">
                                    新增模板
                                </el-button>
                            </span>
                        </template>
                        <el-table :data="item.template_list || []" border>
                            <el-table-column 
                                type="index" 
                                label="序号" 
                                align="center" 
                                width="60">
                            </el-table-column>
                            <el-table-column 
                                prop="name" 
                                label="模板名称" 
                                align="center" 
                                show-overflow-tooltip
                                min-width="130">
                            </el-table-column>
                            <el-table-column 
                                prop="icon" 
                                label="图标" 
                                align="center" 
                                min-width="60">
                                <svg class="icon svg-icon" slot-scope="scope">
                                    <use 
                                        v-if="scope.row.icon"
                                        :xlink:href="`#${scope.row.icon}`">
                                    </use>
                                </svg>
                            </el-table-column>
                            <el-table-column 
                                prop="done_type" 
                                label="若业务目标达成" 
                                :formatter="getAction" 
                                align="center" 
                                show-overflow-tooltip
                                min-width="130">
                            </el-table-column>
                            <el-table-column 
                                prop="fail_type" 
                                label="若业务目标未达成" 
                                :formatter="getAction" 
                                align="center" 
                                show-overflow-tooltip
                                min-width="130">
                            </el-table-column>
                            <el-table-column 
                                prop="add_days" 
                                label="截止时间增加天数" 
                                align="center" 
                                min-width="120">
                            </el-table-column>
                            <template v-if="type == 1">
                                <el-table-column 
                                    prop="class" 
                                    label="触发时间等于" 
                                    :formatter="getTrigger" 
                                    align="center" 
                                    min-width="160" 
                                    show-overflow-tooltip >
                                </el-table-column>
                                <el-table-column 
                                    prop="business_cycle" 
                                    label="基础上加(月)" 
                                    align="center" 
                                    min-width="100">
                                </el-table-column>
                            </template>
                            <el-table-column 
                                prop="display_name" 
                                label="触发时间前端名称" 
                                align="center" 
                                show-overflow-tooltip
                                min-width="140">
                            </el-table-column>
                            <el-table-column label="操作" align="center" min-width="90">
                                <template slot-scope="scope">
                                    <el-button 
                                        icon="el-icon-edit"
                                        type="primary" 
                                        title="编辑模板"
                                        @click.stop="handleDialog('tpl', scope.row)">
                                    </el-button>
                                    <el-button 
                                        icon="el-icon-remove-outline" 
                                        type="danger" 
                                        title="删除模板"
                                        @click.stop="handleDel('tpl', scope.row.id)">
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-collapse-item>
                </el-collapse>
            </el-main>
        </el-container>
        <el-dialog 
            :title="classDialog.title"
  		    :visible.sync="classDialog.visible"
		    :before-close="() => handleDialogClose('class')"
		    custom-class="sop-class-dialog"
		    :close-on-click-modal="false"
            width="560px"
		    append-to-body>
            <el-form 
                :model="classDialog.formData" 
                :rules="classDialog.rules" 
                ref="classFormRef" 
                label-width="92px" 
                size="small">
                <el-form-item prop="name" label="类目名称:">
                    <el-input 
                        v-model="classDialog.formData.name" 
                        maxlength="20" 
                        placeholder="请输入类目名称">
                    </el-input>
                </el-form-item>
                <el-form-item prop="icon" label="类目图标:">
                    <el-input
                        v-model="classDialog.formData.icon" 
                        maxlength="30" 
                        placeholder="图标从iconfont上查找">
                        <template slot="suffix">
                            <svg class="icon svg-icon">
                                <use 
                                    v-if="classDialog.formData.icon"
                                    :xlink:href="`#${classDialog.formData.icon}`">
                                </use>
                                <use v-else xlink:href="#icon-sucai" fill="#cccccc"></use>
                            </svg>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="sort" label="类目排序:">
                    <el-input 
                        v-model.number="classDialog.formData.sort" 
                        maxlength="3" 
                        placeholder="请输入排序">
                    </el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="info" @click="handleDialogClose('class')" size="small">
                    取消
                </el-button>
                <el-button type="primary" @click="handleSubmit('class')" size="small">
                    保存
                </el-button>
            </span>
        </el-dialog>
        <el-dialog 
            :title="tplDialog.title"
  		    :visible.sync="tplDialog.visible"
		    :before-close="() => handleDialogClose('tpl')"
		    custom-class="sop-template-dialog"
		    :close-on-click-modal="false"
            width="520px"
		    append-to-body>
            <el-form 
                :model="tplDialog.formData" 
                :rules="tplDialog.rules" 
                ref="tplFormRef" 
                size="small">
				<el-form-item prop="name" label="模板名称:">
					<el-input 
                        v-model="tplDialog.formData.name" 
                        maxlength="20" 
                        placeholder="请输入模板名称" />
				</el-form-item>
				<el-form-item prop="icon" label="模板图标:">
					<el-input 
                        v-model="tplDialog.formData.icon" 
                        maxlength="30" 
                        placeholder="图标从iconfont上查找" >
                        <template slot="suffix">
                            <svg class="icon svg-icon">
                                <use 
                                    v-if="tplDialog.formData.icon"
                                    :xlink:href="`#${tplDialog.formData.icon}`">
                                </use>
                                <use v-else xlink:href="#icon-sucai" fill="#cccccc"></use>
                            </svg>
                        </template>
                    </el-input>
				</el-form-item>
				<div class="sop-label">
					<span>若业务目标达成</span>
				</div>
				<el-form-item prop="done_type" label="达成后动作:">
					<el-select v-model="tplDialog.formData.done_type" placeholder="请选择动作">
						<el-option 
                            v-for="(item, index) of actionList" 
                            :key="index" 
                            :value="item.id" 
                            :label="item.name">
                        </el-option>
					</el-select>
				</el-form-item>
				<div class="sop-label">
					<span>若业务目标未达成</span>
				</div>
				<el-form-item label-width="0" class="action-fail">
				    <el-form-item prop="add_days" label="则在最后一个动作结束:">
				    	<el-input v-model.number="tplDialog.formData.add_days" maxlength="4">
				    		<span slot="suffix">天后</span>
				    	</el-input>
				    </el-form-item>
                    <i class="el-icon-right" style="color: #cccccc"></i>
				    <el-form-item prop="fail_type" label="执行动作:">
				    	<el-select v-model="tplDialog.formData.fail_type" placeholder="请选择动作">
				    		<el-option 
                                v-for="(item, index) of actionList" 
                                :key="index" 
                                :value="item.id" 
                                :label="item.name">
                            </el-option>
				    	</el-select>
				    </el-form-item>
				</el-form-item>
                <template v-if="type == 1">
				    <div class="sop-label">
				    	<span>本次业务完成后下次的业务触发时间计算方式为</span>
				    </div>
				    <el-form-item label-width="0" class="trigger-time">
				    	<el-form-item prop="class" label="触发时间等于：">
				    		<el-select v-model="tplDialog.formData.class">
						        <el-option 
                                    v-for="(item, index) of triggerList" 
                                    :key="index" 
                                    :value="item.id" 
                                    :label="item.name">
                                </el-option>
				    		</el-select>
				    	</el-form-item>
				    	<el-form-item prop="business_cycle" label="基础上加：">
				    		<el-input v-model.number="tplDialog.formData.business_cycle" maxlength="4">
				    			<span slot="suffix">个月</span>
				    		</el-input>
				    	</el-form-item>
				    </el-form-item>
                </template>
				<el-form-item prop="display_name" label="业务触发时间前端展示名称为:">
					<el-input 
                        v-model="tplDialog.formData.display_name" 
                        maxlength="30" 
                        placeholder="请输入自定义名称"/>
				</el-form-item>
				<el-form-item prop="sort" label="模板排序:">
					<el-input 
                        v-model.number="tplDialog.formData.sort" 
                        maxlength="3" 
                        placeholder="请输入排序" />
				</el-form-item>
			</el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="info" @click="handleDialogClose('tpl')" size="small">
                    取消
                </el-button>
                <el-button type="primary" @click="handleSubmit('tpl')" size="small">
                    保存
                </el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { asyncLoadJs } from '@/common/js/loadResources'
let url = "/templates/js/new-iconfont.js"
if (location.host.includes('localhost')) {
    url = '4s.newweb.com' + url
} else {
    url = location.host.replace('admin','4s') + url
}
asyncLoadJs("//" + url)
export default {
    name: 'sopStoreTemplate',
    data() {
        const validator = function(rule, value, callback) {
        	if (+value < 0) {
        		return callback(new Error('必须 ≥ 0'))
        	} else {
        		return callback()
        	}
        }
        return {
            type: '2',                    // 场景 1 - 循环，2 - 普通 
            typeList: [                   // 场景类型
                { name: '普通场景', id: '2' },
                { name: '循环场景', id: '1' }
            ],
            dataList: [],                 // 类目列表
            activeClassId: [],            // 当前展开的类目
            actionList: [                 // 动作类型
                { name: '继续流程', id: '1' },
                { name: '转移流程', id: '2' },
                { name: '终止流程', id: '3' }
            ],
            triggerList: [                // 业务完成触发场景
                { name: '基于客户实际的业务完成时间', id: '1' },
                { name: '基于客户固定的业务完成时间', id: '2' }
            ],
            classDialog: {                // 类目dialog
                visible: false,
                title: '新增类目',
                formData: {
                    id: '',               // 类目ID，存在视为编辑，否则添加
                    name: '',             // 类目名称
                    icon: '',             // 类目图标
                    sort: ''              // 排序
                },
                rules: {
                    name: [
                        { required: true, message: '请填写类目', trigger: ['blur', 'change'] }
                    ],
				    icon: [
                        { required: true, message: '请添加类目图标', trigger: ['blur', 'change'] }
                    ],
				    sort: [
                        { required: true, message: '请填写排序', trigger: ['blur', 'change'] },
                        { type: 'number', message: '请输入整数', trigger: ['blur', 'change'] },
                        { type: 'number', validator, trigger: ['blur', 'change'] }
                    ]
                }
            },
            tplDialog: {                  // 模板dialog
                visible: false,
                title: '新增模板',
                formData: { 
                    id: '',               // 模板ID，存在视为编辑，否则添加
                    name: '',             // 模板名称
                    icon: '',             // 模板图标
                    done_type: '',        // 达成动作流程类型
                    add_days: '',         // 多少天后执行未达成动作方案
                    fail_type: '',        // 未达成动作流程类型
                    class: '',            // 触发时间等于
                    business_cycle: '',   // 基础上加
                    display_name: '',     // 自定义业务触发时间前端展示名称
                    sort: ''              // 排序
                },
                rules: {
                    name: [
                        { required: true, message: '请填写模板名称', trigger: ['blur', 'change'] }
                    ],
				    icon: [
                        { required: true, message: '请添加模板图标', trigger: ['blur', 'change'] }
                    ],
				    done_type: [
                        { required: true, message: '请选择达成后动作', trigger: 'change' }
                    ],
				    add_days: [
				    	{ required: true, message: '请填写天数', trigger: ['blur', 'change'] },
				    	{ type: 'number', message: '请输入整数', trigger: ['blur', 'change'] },
                        { 
                            type: 'number', 
                            validator: function(rule, value, callback) {
                            	if (+value <= 0) {
                            		return callback(new Error('必须 > 0'))
                            	} else {
                            		return callback()
                            	}
                            }, 
                            trigger: ['blur', 'change'] 
                        }
                    ],
				    fail_type: [
                        { required: true, message: '请选择达未成后动作', trigger: 'change' }
                    ],
				    class: [
                        { required: true, message: '请选择触发时间等于', trigger: 'change' }
                    ],
				    business_cycle: [
				    	{ required: true, message: '请填写月数', trigger: ['blur', 'change'] },
				    	{ type: 'number', message: '请输入整数', trigger: ['blur', 'change'] },
                        { type: 'number', validator, trigger: ['blur', 'change'] }
				    ],
				    sort: [
                        { required: true, message: '请填写排序', trigger: ['blur', 'change'] },
                        { type: 'number', message: '请输入整数', trigger: ['blur', 'change'] },
                        { type: 'number', validator, trigger: ['blur', 'change'] }
                    ]
                }
            }
        }
    },
    computed: {
        getList() {
            return this.dataList.filter(item => item.type == this.type)
        }
    },
    methods: {
        handleDialog(type = 'class', row = {}) {
            const obj = this[type + 'Dialog']
            const label = type === 'class' ? '类目' : '模板'
            obj.visible = true
            obj.title = '新增' + label
            if (row.id) {
                obj.title = '编辑' + label
                row.sort = +row.sort
                row.add_days = row.add_days ? +row.add_days : row.add_days
                if (type == 'tpl') {
                    row.business_cycle = +row.business_cycle
                }
            }
            this.$nextTick(() => {
                obj.formData = { ...obj.formData, ...row }
            })
        },
        handleDialogClose(type = 'class') {
            this.$refs[type + 'FormRef'].resetFields()
            this[type + 'Dialog'].visible = false
        },
        handleSubmit(type = 'class') {
            let url = '/admin/sop/index.php?act=sopGroup&op=save'
            if (type == 'tpl') {
                url = '/admin/sop/index.php?act=sop&op=save'
                if (this.type == 2) {
                    this[type + 'Dialog'].formData.business_cycle = 0
                } 
            }
            this.$refs[type + 'FormRef'].validate(valid => {
                if (valid) {
                    const datas = { ...this[type + 'Dialog'].formData, type: this.type }
                    this.$http.post(url, datas)
                    .then(res => {
                        if (res.code == 200) {
                            this.$message.success('保存成功')
                            this.handleDialogClose(type)
                            this.getData()
                        } else {
                            this.$message.error(res.msg)
                        }
                    }).catch(error => {
                        error && this.$message.error(`${error}`)
                    })
                }
            })
        },
        handleDel(type = 'class', id) {
            let content = '确定删除该类目吗？删除则对应的模板也会被删除。'
            let url = '/admin/sop/index.php?act=sopGroup&op=del'
            if (type == 'tpl') {
                content = '确定删除该模板吗？'
                url = '/admin/sop/index.php?act=sop&op=del'
            }
            this.$alert(
                content, 
                '温馨提示', 
                {
                    type: 'warning',
                    showCancelButton: true
                }
            ).then(() => {
                this.$http.get(url, { params: { id } })
                .then(res => {
                    if (res.code == 200) {
                        this.$message.success('删除成功')
                        this.getData()
                    } else {
                        this.$message.error(res.msg)
                    }
                }).catch(error => {
                    error && this.$message.error(`${error}`)
                })
            }).catch(() => {})
        },
        getData() {
            this.$http.get('/admin/sop/index.php?act=sop&op=list', { type: this.type })
            .then(res => {
                if (res.code == 200) {
                    this.dataList = res.data || []
                    this.activeClassId = this.dataList.map(item => item.id)
                } else {
                    this.$message.error(res.msg)
                }
            }).catch(error => {
                error && this.$message.error(`${error}`)
            })
        },
        getAction(row, column, cellValue, index) {
            const action = this.actionList.find(item => item.id == cellValue) || {}
            return action.name
        },
        getTrigger(row, column, cellValue, index) {
            const action = this.triggerList.find(item => item.id == cellValue) || {}
            return action.name
        }
    },
    created() {
        this.getData()
    }
}
</script>
<style scoped lang="scss">
.container {
    border: 1px solid #E4E7ED;
    height: calc(100% - 58px);
    margin-top: 16px;
    box-sizing: border-box;
    padding: 18px;
}
.el-container {
    height: 100%;
}
.left-menu /deep/ {
    max-width: 132px;
    text-align: right;
    margin-right: 16px;
    position: relative;
    height: 100%;
    .el-tabs {
        height: 100%;
        box-sizing: border-box;
        position: relative;
    }
    .el-tabs__header.is-left {
        float: right;
    }
    .el-tabs__nav-scroll {
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
        &::-webkit-scrollbar {
            width: 2px;
        }
    }
    .el-tabs__nav-prev,
    .el-tabs__nav-next {
        display: none;
    }
    .el-tabs__nav-wrap.is-left.is-scrollable {
        padding-top: 0;
        padding-bottom: 50px;
    }
    .el-tabs__item {
        padding: 0 38px;
    }
    .add-menu {
        position: absolute;
        right: 31px;
        bottom: 0;
        z-index: 2;
        height: 33px;
        .el-icon {
            font-size: 13px;
        }
    }
}
.el-main {
    padding: 0;
    .no-data {
        background: url('~@/assets/images/sop-index-bg.jpg') no-repeat center;
    }
}
.el-collapse /deep/ {
    border-width: 0;
    .el-collapse-item__header {
        border: 1px solid #E4E7ED;
        border-radius: 3px 3px 0 0;
        // background-color: #F5F7FA;
        background-image: linear-gradient(to right, #F5F7FA, #fff);
        padding: 0 8px 0 16px;
        position: relative;
        height: 43px;
        line-height: 1;
        h3 {
            font-size: 14px;
            margin-right: 4px;
            margin-left: 16px;
        }
        .tpl-total {
            color: #F56C6C;
            padding-bottom: 1px;
        }
        .el-collapse-item__arrow {
            position: absolute;
            left: 12px;
            z-index: 10;
            top: 14px;
        }
        .control-btn {
            position: absolute;
            right: 16px;
            top: 6px;
            box-sizing: border-box;
            .el-button + .el-button {
                margin-left: 14px;
            }
            .el-button span {
                margin-left: 0;
            }
        }
    }
    .el-collapse-item__content {
        padding-bottom: 0;
    }
    .el-collapse-item__wrap {
        border-width: 0;
    }
    .el-collapse-item {
        margin-bottom: 16px;
    }
    .el-table {
        margin-top: -1px;
        .el-button {
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 25px;
            height: 25px;
            padding: 0;
        }
    }
}
//滚动条的宽度
.el-container ::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}
//滚动条的滑块
.el-container ::-webkit-scrollbar-thumb {
    cursor: pointer;
    background-color: rgba(144, 147, 153, 0.25);
    background-clip: padding-box;
    border-right: 1px solid transparent;
    border-bottom: 1px solid transparent;
    border-radius: 6px;
}
</style>
<style lang="scss">
.el-dialog .el-dialog__body {
    padding-top: 16px;
    padding-bottom: 0;
}
.sop-class-dialog {
    .el-dialog__body {
        padding: 20px 25px 10px 20px;
    }
    .el-dialog__footer {
        padding: 5px 25px 18px 20px;
    }
}
.sop-template-dialog {
    .el-form-item__label {
        width: 100%;
        text-align: left;
        line-height: 100%;
        padding-bottom: 8px;
        display: block;
    }
    .sop-label {
        padding-bottom: 10px;
        font-weight: bold;
        color: #999;
        margin-top: -3px;
    }
    .el-select, .el-input {
        width: 100%;
    }
    .action-fail {
        margin-bottom: 0;
        > .el-form-item__content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-right: 0;
            &::before, &::after {
                content: none;
            }
            .el-form-item {
                width: calc(50% - 18px);
            }
        }
        .el-input__suffix-inner {
            margin-right: 6px;
        }
    }
    .trigger-time {
        margin-bottom: 0;
        > .el-form-item__content {
            display: flex;
            align-items: center;
            .el-form-item {
                flex-grow: 1;
                width: 100%;
                &:nth-child(2) {
                    flex-grow: 1;
                    width: calc(40% - 16px);
                    margin-left: 16px;
                }
            }
        }
    }
}
.svg-icon {
	width: 16px;
	height: 16px;
    margin: 0 4px -1px 0;
    fill: #409EFF;
}
</style>